import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: '',
    userInfo: JSON.parse(sessionStorage.getItem("userInfo")),
    visited: JSON.parse(sessionStorage.getItem("visited"))
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      localStorage.setItem("token", token)
    },
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = {
        id: userInfo.id,
        username: userInfo.username,
        authority: userInfo.authority,
        gender: userInfo.gender,
        birthday: userInfo.birthday,
        email: userInfo.email,
        phone: userInfo.phone,
        address: userInfo.address,
        status: userInfo.status,
        score: userInfo.score
      }
      sessionStorage.setItem("userInfo", JSON.stringify(userInfo))
    },
    REMOVE_INFO: (state) => {
      localStorage.setItem("token", '')
      sessionStorage.setItem("userInfo", JSON.stringify({ valid: false }))
      state.userInfo = { valid: false }
    },
    ADD_VISITED: (state, product) => {
      if (state.visited === null) {
        state.visited = {}
      }
      state.visited[product.id] = product
      sessionStorage.setItem("visited", JSON.stringify(state.visited))
    },
    REMOVE_VISITED: (state) => {
      sessionStorage.setItem("visited", JSON.stringify({}))
      state.visited = {}
    }
  },
  getters: {
    getUser: state => {
      return state.userInfo
    },
    getVisited: state => {
      return state.visited
    }
  },
  actions: {},
  modules: {}
})
